<?php

/**
 * HarmonogramController
 * 
 * @author Radovan Dvorsky
 * @version 20100604
 */

require_once 'Zend/Controller/Action.php';

class HarmonogramController extends Zend_Controller_Action {
	
	public function init(){
		$contextSwitch = $this->_helper->getHelper('AjaxContext');
        $contextSwitch->addActionContext('delete', 'html')
        ->addActionContext('generate-harmonograms-table','html')
        ->addActionContext('fill-student','html')
        ->addActionContext('fill-group','html')
        ->addActionContext('change','html')
        ->initContext();
	}
	
	/**
	 * The default action - zobrazí všetky harmonogmy v tabulke
	 */
	public function indexAction() {
		
		$cache = Zend_Registry::get('cache');		
		$cacheName = My_Support::getCacheName($this,'fetchAll');
		$commissions = array();
						
		/*
		 * Nacitaj data z cache ak existuje
		 * 
		 * pozn. Data z databaze je treba selectovat zvlast z tabulky Harmonogram a Student, nakolko
		 * tabulka Harmonogram sa nachaza v databaze kosilky a tabulka Student v skolskej databaze
		 */
		if(!($harmonograms = $cache->load($cacheName))){			
			$harmonogramMapper = new Db_Mapper_Harmonogram();
			$select = $harmonogramMapper->getTable()->select();
			$select->order('ord');			
			$harmonograms = $harmonogramMapper->fetchAll($select);
			$cache->save($harmonograms,$cacheName,array(get_class($this)));
		}		
		
		
		$cacheNameCommissions = My_Support::getCacheName('CommissionController','fetchAll');
		
		if(!($commissionsTmp = $cache->load($cacheNameCommissions))){
			$commissionMapper = new Db_Mapper_Commission();
			$commissionsTmp = $commissionMapper->fetchAll();
			$cache->save($commissionsTmp,$cacheNameCommissions);
		}
		
		foreach($commissionsTmp as $commission){
			$commissions[$commission->cid] = $commission->name;
		}
		
		$studentCacheName = My_Support::getCacheName($this,'fetchWithGroups');
		
		/**
		 * POZOR: Cache sa nikde neodstranuje, takze sa cache obnovuje len automaticky po
		 * 2 hodinách, takže každá zmena v školskej DB sa neprejaví okamžite ak 
		 * sa cache explicitne nevymaze pomocou $cache->clean()
		 */
		if(!($students = $cache->load($studentCacheName))){
			$studentMapper = new Db_Mapper_Student();
			$students = $studentMapper->fetchStudentsWithGroups();
			$cache->save($students,$studentCacheName,array('students'));			
		}

				
		/*
		 * Z dat vytvor pole, ktore sa bude posielat do view 
		 */
		foreach($students as $student){
			$studentsView[$student->ID_st] = array(				
					'Jmeno' => $student->Jmeno,
					'Prijmeni' => $student->Prijmeni,
					'Odbor' => $student->Zkratka,			
			);
		}		
		
		
		/*
		 * Pole harmonogramov a studentov posli do view
		 */		
		$this->view->harmonograms = $harmonograms;	
		$this->view->students = $studentsView;		
		$this->view->commissions = $commissions;
	}
	
	
	/**
	 * Vytvára nové harmongramy
	 */
	public function addAction(){
		$form = new Form_Harmonogram_Add();
		$this->view->form = $form;
						
		/*
		 * Ak je odoslany formular
		 */
		if($this->getRequest()->isPost()){
			
			$formData = $this->getRequest()->getPost();
			/*
			 * Kontrola zadanych udajov
			 */
			if($form->isValid($formData)){
				try{					
					$harmonogramMapper = new Db_Mapper_Harmonogram();					
					$adapter = $harmonogramMapper->getTable()->getAdapter();
					
					$adapter->beginTransaction();
					
					/*
					 * Ak je zadany datum, tak vytvor Zend_Date
					 */
					if(!empty($formData['date'])){
						$date = new Zend_Date($form->getValue('date'),'dd-MM-YYYY'); 
					} 
					
					/*
					if (!empty($formData['block2'])){
						$block2 = new Zend_Date($form->getValue('block2'),'dd-MM-YYYY');
					}
					if(!empty($formData['bcdate'])){
						$bcdate = new Zend_Date($form->getValue('bcdate'),'dd-MM-YYYY');
					}
					*/
					
					$harmonogramCount = $harmonogramMapper->getHarmonogramsCount();
					
					/*
					 * Ak este nie je v databaze ziadny harmonogram tak vloz 0 (tj. prvy v poradi)
					 * inak vloz pocet harmonogramov + 1
					 */
					$ord = $harmonogramCount == 0 ? 0 : $harmonogramCount++;
					
					/*
					 * Vytvori pole dat, ktore sa vlozi do databaze
					 */	
					$data = array(
						'cidBc' => (int)$form->getValue('cidBc'),
						'cidBlock1' => (int)$form->getValue('cidBlock1'),
						'cidBlock2' => (int)$form->getValue('cidBlock2'),
						'ord' => (int)$ord,
						'ID_st' => (int)$form->getValue('ID_st'),						
						//Konvertuje zadany datum do formatu vhodneho na ulozenie do databaze
						'date' => !empty($date) ? $date->toString('YYYY-MM-dd') : NULL,						
					);
					
					/*
					 * Vloz data do databaze
					 */
					$harmonogramMapper->save(new Db_Model_Harmonogram($data));
					
					/*
					 * Vyprazdni chache pre harmonogramy
					 */
					$cache = Zend_Registry::get('cache');
					$cache->remove(My_Support::getCacheName($this,'fetchAll'));
					
					/*
					 * Na zaklade id studenta a aktualneho roka zisti id triedy
					 */
					$studentHasTridyMapper = new Db_Mapper_StudentHasTridy();
					$skRokMapper = new Db_Mapper_SkRok();
					$year = $skRokMapper->getActual();
					$where = $studentHasTridyMapper->getTable()->select();
					$where->where('Student_ID_st = ?',$form->getValue('ID_st'),Zend_Db::INT_TYPE)
					->where('skolni_rok = ?',$year->getID_sk(),Zend_Db::INT_TYPE);
					$studentHasTridyModel = $studentHasTridyMapper->fetchRow($where);					
					
					/*
					 * Odstrani cache pre result controller podla id triedy
					 */
					$cache->clean(
						Zend_Cache::CLEANING_MODE_MATCHING_TAG,
						array('Result_ShowUser_ID_tr'.$studentHasTridyModel->getTridy_ID_tr())
					);
					
					/*
					 * Commit
					 */
					$adapter->commit();
					
					/*
					 * Vycisti formular
					 */
					$form->reset();
					
					$this->view->message = '<p class="success">Harmonogram pridaný</p>';					
					
				} catch( Zend_Exception $e){
					$adapter->rollBack();
					/*
					 * Ak je chyba vloz ju do logu
					 */					
					$log = Zend_Registry::get('log');    		
    				$log->log(get_class($e) . ':' . $e->getMessage(),Zend_Log::ERR);
    				/*
    				 * Do view posli spravu o chybe
    				 */
    				$this->view->message = '<p class="error">Harmonogram sa nepodarilo vytvoriť</p>';
				}				
			}
		}
	}
	
	
	/**
	 * Na základe prijateho parametru <code>id</code>(zoznam hodnôt 
	 * oddelených čiarkou) odstráni data z databáze.
	 */
	public function deleteAction(){		
		/*
		 * Ziskaj hodnoty (json)
		 */
		$hidPost = $this->getRequest()->getParam('id');
			
		if(!empty($hidPost)){
			/*
			 * Vytvor pole
			 */
			$hids = explode(',',$hidPost);	
			try{
								
				$harmonogramMapper = new Db_Mapper_Harmonogram();
				foreach($hids as $hid){					
					$harmonogramMapper->delete(new Db_Model_Harmonogram(array('hid' => (int)$hid)));					
				}
				
				$harmonogramMapper->orderHarmonograms();
					
				$cache = Zend_Registry::get('cache');
				$cache->remove(My_Support::getCacheName('HarmonogramController','fetchAll'));
					
				/*
                 * TODO: Maze komplet cache, treba prerobit, aby mazalo len cache
                 * pre resultController a daneho studenta
                 */
                $cache->clean();
				
				$this->view->message = '<p class="success">Harmonogramy odstránené</p>';			
					
			}catch(Zend_Db_Exception $e){
				$this->view->message = '<p class="success">Harmonogramy sa nepodarilo odstrániť</p>';
				$log = Zend_Registry::get('log');    		
		   		$log->log(get_class($e) . ':' . $e->getMessage(),Zend_Log::ERR);
			}
		}
	}
	
	
	/**
	 * Action príjma dva parametre (post), <code>origId</code> a <code>newId</code
	 * 
	 * Mení poradie harmonogramov v databáze
	 */
	public function changeAction(){
		
		$origId = $this->getRequest()->getParam('origId');
		$newId = $this->getRequest()->getParam('newId');
		
		if(isset($origId) && isset($newId)){
			
			try{
				$harmonogramMapper = new Db_Mapper_Harmonogram();
				$harmonogramMapper->changePosition($origId,$newId);
				
				//$harmonogramModel->orderHarmonograms();
								
				$cache = Zend_Registry::get('cache');
				$cache->remove(My_Support::getCacheName('HarmonogramController','fetchAll'));
				
			} catch(Zend_Db_Exception $e){
				$log = Zend_Registry::get('log');    		
	    		$log->log(get_class($e) . ':' . $e->getMessage(),Zend_Log::ERR);
			}
			
		}else {
			$this->_redirect('/harmonogram/');
		}
		
	}
	
	/**
	 * Sluzi na vyplnenie mena vo formulari na pridanie harmonogramu
	 */	
	public function fillStudentAction(){
		
		$ID_tr = (int) $this->getRequest()->getParam('ID_tr');
		$ID_sk = (int)$this->getRequest()->getParam('ID_sk');
		
		$cache = Zend_Registry::get('cache');
		$cacheName = My_Support::getCacheName($this,'group'.$ID_tr.$ID_sk);
		
		
		if(!($group = $cache->load($cacheName))){
			
			$studentMapper = new Db_Mapper_Student();
			$group = $studentMapper->fetchActualStudents(
				new Db_Model_SkRok(array('ID_sk' => $ID_sk)),
				new Db_Model_TTridy(array('ID_tr' => $ID_tr))
			);		
			
			$cache->save($group,$cacheName);
		}
		
		$this->view->group = $group;
		
	}
	
	/**
	 * Sluzi na vyplnenie triedy vo formulari na pridanie harmonogramu
	 */
	public function fillGroupAction(){
		
		$ID_sk = (int)$this->getRequest()->getParam('ID_sk');
		
		$cache = Zend_Registry::get('cache');
		$cacheName = My_Support::getCacheName($this,'fillGroup'.$ID_sk);
				
		if(!($groups = $cache->load($cacheName))){
			$TTridyMapper = new Db_Mapper_TTridy();
			$groups = $TTridyMapper->fetchGroupsForYear(new Db_Model_SkRok(array('ID_sk' => $ID_sk)));
			$cache->save($groups,$cacheName);			
		}
		
		$this->view->groups = $groups;		
	}
}